package com.atguigu.gulimall.order.web;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebontroller {

    @Autowired
    OrderService orderService;

    //点击去结算，跳到订单确认页
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {

        //这一段也要去查到最新的数据，因为数据库的价格可能修改了
        OrderConfirmVo confirmVo = orderService.confirmOrder();

        model.addAttribute("orderConfirmData",confirmVo);
        return "confirm";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes){

        try{

            SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);

            //下单，去创建订单，验证令牌，验证价格，锁库存

            if(responseVo.getCode() == 0){

                //下单成功来到支付选择页面
                //来到支付页面

                model.addAttribute("submitOrderResp",responseVo);

                return "pay";

            }else{

                String msg = "";

                switch (responseVo.getCode()){
                    case 1: msg+="令牌失败";break;
                    case 2: msg+="验证价格失败";break;
                }

                redirectAttributes.addFlashAttribute("msg",msg);

                return "redirect:http://order.gulimall.com/toTrade";
            }

        }catch (NoStockException e){

            redirectAttributes.addFlashAttribute("msg","库存不足");

            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
